package com.ellwood.common.core.xss;

import com.ellwood.common.core.utils.EllStrUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ProjectName: Ellwood-framework-boot
 * @PackageName: com.ellwood.common.core.xss
 * @ClassName: XssValidator
 * @Description: // 自定义xss校验注解实现
 * @Author: Ellwood
 * @CreateDate: 2024/7/13 - 上午1:11
 * @Version: V1.0.0
 */
public class XssValidator implements ConstraintValidator<Xss, String> {

    private static final String HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />";

    public static boolean containsHtml(String value) {
        Pattern pattern = Pattern.compile(HTML_PATTERN);
        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        return EllStrUtil.isBlank(value) || !containsHtml(value);
    }
}
